package com.ts.api.module.protocol.service.impl;

import com.gitee.apanlh.util.base.IteratorUtils;
import com.gitee.apanlh.util.date.DateUtils;
import com.gitee.apanlh.util.valid.ValidParam;
import com.ts.api.module.channel.entity.po.ChannelUserRegisterPO;
import com.ts.api.module.channel.entity.qo.ChannelUserQO;
import com.ts.api.module.channel.service.ChannelUserService;
import com.ts.api.module.protocol.entity.bo.ProtocolTemplateBO;
import com.ts.api.module.protocol.entity.po.ProtocolPO;
import com.ts.api.module.protocol.service.ProtocolService;
import com.ts.api.module.protocol.service.ProtocolTemplateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ProtocolTemplateServiceImpl implements ProtocolTemplateService {

    @Autowired
    private ChannelUserService channelUserService;
    @Autowired
    private ProtocolService protocolService;

    @Override
    public ProtocolTemplateBO getUserTemplate(String phone) {
        ProtocolTemplateBO protocolTemplateBO = new ProtocolTemplateBO();

        //  获取用户信息
        ChannelUserQO channelUserQO = ChannelUserQO.createPhone(phone);
        ChannelUserRegisterPO channelUserRegisterPO = channelUserService.get(channelUserQO);

        if (ValidParam.isNull(channelUserRegisterPO)) {
            return protocolTemplateBO;
        }

        protocolTemplateBO.setUserPhone(channelUserRegisterPO.getPhone());
        protocolTemplateBO.setUserAccount(channelUserRegisterPO.getPhone());
        protocolTemplateBO.setUserName(channelUserRegisterPO.getUserName());
        protocolTemplateBO.setCurrentDate(DateUtils.currentTime("yyyy年MM月dd日"));
        protocolTemplateBO.setIdcard(channelUserRegisterPO.getIdcard());
        return protocolTemplateBO;
    }

    @Override
    @Transactional(readOnly = true)
    public String replaceByOrder(String unicode, ProtocolTemplateBO protocolTemplateBO) {
        ProtocolPO protocolText = protocolService.getProtocolText(unicode);
        String text = protocolText.getText();

        StringBuilder sb = new StringBuilder(text);

        IteratorUtils.entrySet(protocolTemplateBO.toOrderMap(), (k, v) -> {
            String search = "${" + k + "}";
            int indexOf = sb.lastIndexOf(search);
            if (indexOf != -1) {
                sb.replace(indexOf, indexOf + search.length(), v);
            }
        });
        return sb.toString();
    }
}
